import React, { Component } from "react";
import { connect } from "dva";
import {
  Form,
  Button,
  Steps,
  Icon,
  Divider,
  TreeSelect,
  Table,
  Breadcrumb,
  Modal
} from "antd";
import { Link } from "dva/router";
import { gup } from "../../utils/utils";
import PartmentButton from "../../components/PartmentButton";
import {
  getTreeperBydepart, //部门人员
  taskAttendanceComAttendGroupFindAttendGroupByPerIdStr, //新增考勤组-设置考勤人员-检查多个人员是否存在于其他考勤组
  taskAttendanceComAttendGroupInThirdStepAttendGroup, //进入考勤组设置-第三步页面
  taskAttendanceComAttendGroupSaveThirdStepAttendGroup, //新增或者修改考勤组-第三步-设置考勤人员并保存
  taskAttendanceComAttendGroupCheckAttendPer //新增或者修改考勤组-设置考勤人员-检查人员是否存在于其他考勤组
} from "../../services/api";

import "./ThiftManagement.less";

const { confirm } = Modal;
const FormItem = Form.Item;
const { Step } = Steps;

@connect(state => ({
  global: state.global,
  currentuser: state.user
}))
@Form.create()
export default class SettingUpAttendance extends Component {
  constructor(props, context) {
    super(props, context);
    console.log(this, "this");
    this.state = {
      perIdStr: [],
      perIdList: [],
      chargePerIdStr: "",
      chargePerIdList: [],
      attendGroupId: gup("attendGroupId") || "",
      midAttendGroupId: gup("midAttendGroupId") || "",
      chargePerVisible: false,
      treeData: [],
      arrayObj:[]
    };
  }

  componentDidMount() {
    this.getTreeperBydepart();
    this.taskAttendanceComAttendGroupInThirdStepAttendGroup();
  }

  renderTable = data => {
    if (data) {
      data = JSON.parse(data);
    } else {
      return null;
    }
    const dataSource = data.map((val, i) => {
      val.key = i;
      return val;
    });
    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        key: "1",
        width: 80
      },
      {
        title: "考勤组",
        dataIndex: "attendGroupName",
        key: "2"
      }
    ];

    return <Table size="small" dataSource={dataSource} columns={columns} />;
  };
  //新增考勤组-设置考勤人员-检查多个人员是否存在于其他考勤组
  taskAttendanceComAttendGroupFindAttendGroupByPerIdStr = chargePerIdStr => {
    taskAttendanceComAttendGroupFindAttendGroupByPerIdStr({
      perIdStr: chargePerIdStr.join(",")
    }).then(
      response => {
        console.log(
          response,
          "response-新增考勤组-设置考勤人员-检查多个人员是否存在于其他考勤组-taskAttendanceComAttendGroupFindAttendGroupByPerIdStr"
        );
        if (response.data.length > 0) {
          confirm({
            title: "以下人员都已经有考勤任务了",
            content: this.renderTable(response.data),
            okText: "确认调整",
            cancelText: "保持不变",
            onOk: () => {},
            onCancel: () => {
              this.taskAttendanceComAttendGroupInThirdStepAttendGroup();
            }
          });
        }
      },
      err => {
        console.log(
          err,
          "err-新增考勤组-设置考勤人员-检查多个人员是否存在于其他考勤组-taskAttendanceComAttendGroupFindAttendGroupByPerIdStr"
        );
      }
    );
  };

  //新增或者修改考勤组-设置考勤人员-检查人员是否存在于其他考勤组
  taskAttendanceComAttendGroupCheckAttendPer = () => {
    const { midAttendGroupId, perIdStr, attendGroupId } = this.state;
    taskAttendanceComAttendGroupCheckAttendPer({
      midAttendGroupId,
      perIdStr: perIdStr.join(","),
      attendGroupId
    })
      .then(res => {
        console.log(
          res,
          "新增或者修改考勤组-设置考勤人员-检查人员是否存在于其他考勤组-res"
        );
        if (res.data) {
          console.log(res.data, "res.data");
          confirm({
            title: "以下人员都已经有考勤任务了",
            content: this.renderTable(res.data),
            okText: "确认调整",
            cancelText: "保持不变",
            onOk: () => {
              confirm({
                title: "选择考勤生效时间",
                content: '若选择"立即生效"，今天相关的考勤记录会重新核算',
                okText: "即时生效",
                cancelText: "明日生效",
                onOk: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    "1",
                    "1"
                  );
                },
                onCancel: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    "1",
                    "2"
                  );
                }
              });
            },
            onCancel: () => {
              confirm({
                title: "选择考勤生效时间",
                content: '若选择"立即生效"，今天相关的考勤记录会重新核算',
                okText: "即时生效",
                cancelText: "明日生效",
                onOk: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    "0",
                    "1"
                  );
                },
                onCancel: () => {
                  this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                    "0",
                    "2"
                  );
                }
              });
            }
          });
        } else {
          confirm({
            title: "选择考勤生效时间",
            content: '若选择"立即生效"，今天相关的考勤记录会重新核算',
            okText: "即时生效",
            cancelText: "明日生效",
            onOk: () => {
              this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                "0",
                "1"
              );
            },
            onCancel: () => {
              this.taskAttendanceComAttendGroupSaveThirdStepAttendGroup(
                "0",
                "2"
              );
            }
          });
        }
      })
      .catch(err =>
        console.log(
          err,
          "新增或者修改考勤组-设置考勤人员-检查人员是否存在于其他考勤组-err"
        )
      );
  };

  //新增或者修改考勤组-第三步-设置考勤人员并保存
  taskAttendanceComAttendGroupSaveThirdStepAttendGroup = (
    isAdjust,
    effectRule
  ) => {
    const { midAttendGroupId, attendGroupId, chargePerIdStr } = this.state;
    console.log(
      {
        midAttendGroupId,
        attendGroupId,
        isAdjust,
        effectRule,
        chargePerIdStr
      },
      `{
      midAttendGroupId,
      attendGroupId,
      isAdjust,
      effectRule,
      chargePerIdStr
    }`
    );
    taskAttendanceComAttendGroupSaveThirdStepAttendGroup({
      midAttendGroupId,
      attendGroupId,
      isAdjust,
      effectRule,
      chargePerIdStr
    })
      .then(res => {
        console.log(res, "新增或者修改考勤组-第三步-设置考勤人员并保存-res");
        this.props.history.push(`/attendancemanagement/settingcomplete`);
      })
      .catch(err =>
        console.log(err, "新增或者修改考勤组-第三步-设置考勤人员并保存-err")
      );
  };
  //进入考勤组设置-第三步页面
  taskAttendanceComAttendGroupInThirdStepAttendGroup = () => {
    const { midAttendGroupId, attendGroupId } = this.state;
    taskAttendanceComAttendGroupInThirdStepAttendGroup({
      midAttendGroupId,
      attendGroupId
    }).then(
      response => {
        console.log(response, "response-进入考勤组设置-第三步页面");
        const { setFieldsValue } = this.props.form;
        if (
          !("perList" in response.data) ||
          !("chargePerList" in response.data)
        ) {
          return null;
        }
        const { perList, chargePerList } = response.data;
        const newlist1 = perList.map(val => {
          return val.perId;
        });
        const newlist = perList.map(val => {
          return `${val.perId}::${val.name}`;
        });
        if (perList.length) {
          this.setState({
            perIdStr: newlist1
          });
          setFieldsValue({
            perIdStr: newlist
          });
        }

        if (chargePerList.length > 0) {
          this.setState({
            chargePerIdStr: chargePerList[0]["perId"],
            chargePerIdList: [{ title: chargePerList[0]["name"] }],
            arrayObj:chargePerList
          });
          setFieldsValue({
            chargePerIdStr: chargePerList[0]
          });
        }
      },
      err => {
        console.log(
          err,
          "err-进入考勤组设置-第三步页面taskAttendanceComAttendGroupInThirdStepAttendGroup"
        );
      }
    );
  };

  gerator = data => {
    return data.map(val => {
      val.value = `${val.key}::${val.label}`;
      if (val.treeType === "1") {
        val.value = `${val.key}::${val.label}::dept`;
      }
      if (val.children.length > 0) {
        val.children = this.gerator(val.children);
      }
      return val;
    });
  };

  //部门人员
  getTreeperBydepart = () => {
    getTreeperBydepart().then(
      response => {
        console.log(response, "response-部门人员-getTreeperBydepart");
        console.log(this.gerator(response.data));
        this.setState({ treeData: response.data });
      },
      err => {
        console.log(err, "err-部门人员-getTreeperBydepart");
      }
    );
  };

  //宣染参与人员
  perIdListRender = () => {
    return this.state.perIdList.map((val, i) => {
      console.log(val, i);
      return (
        <span key={i} className="user">
          <Icon type="user" />
          {val.title}
        </span>
      );
    });
  };

  //宣染人员选择器
  renderUserSelect = () => {
    const { setFieldsValue } = this.props.form;
    /* 考勤组负责人: */
    return (
      <PartmentButton
        onCheck={(chargePerIdStr, chargePerIdList) => {
          console.log(chargePerIdStr, chargePerIdList, "PartmentButton");
          this.setState({
            chargePerVisible: false,
            chargePerIdStr,
            chargePerIdList
          });
          setFieldsValue({ chargePerIdStr });
        }}
        type="radio"
        handleCancel={() => {
          this.setState({
            chargePerVisible: false
          });
        }}
        value={this.state.chargePerIdStr}
        arrayObj={this.state.arrayObj}
        visible={this.state.chargePerVisible}
      />
    );
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(err, values, "err-values");
      if (!err) {
        this.taskAttendanceComAttendGroupCheckAttendPer();
      }
    });
  };

  onChange = value => {
   // console.log("onChange ", value, arguments);
    this.setState({ perIdStr: value });
  };

  findper = perIdStr => {
    clearTimeout(this.timeId);
    this.timeId = window.setTimeout(() => {
      this.taskAttendanceComAttendGroupFindAttendGroupByPerIdStr(perIdStr);
    }, 1000);
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 }
      }
    };

    return (
      <div className="CreateTask ThiftManagement">
        <div className="card-breadcrumb">
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/attendancemanagement/newattendanceunit">
                考勤组管理
              </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>设置考勤人员</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="card">设置考勤人员</div>
        <div className="Steps">
          <Steps current={2}>
            <Step title="选择考勤类型" />
            <Step title="考勤地点" />
            <Step title="设置考勤人员" />
            <Step title="完成" />
          </Steps>
        </div>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout} label="选择需要参与考勤的人员">
            {getFieldDecorator("perIdStr", {
              initialvalue: this.state.perIdStr,
              rules: [{ required: true, message: "请选择参与人员" }]
            })(
              <TreeSelect
                treeData={this.state.treeData}
                treeCheckable
                onChange={(perIdStr, label, extra) => {
                  console.log(perIdStr, extra, "perIdStr-onChange");
                  const { setFieldsValue } = this.props.form;
                  let newarr = perIdStr.filter(val => {
                    if (val.indexOf("dept") > 0) {
                      console.log(val);
                    }
                    return val.indexOf("dept") === -1;
                  });
                  newarr = newarr.map(val => val.split("::")[0]);
                  console.log(newarr, perIdStr, "newarr,perIdStr");
                  setFieldsValue({ perIdStr: newarr });
                  this.setState({ perIdStr: newarr });
                  //this.findper(newarr);
                }}
                showCheckedStrategy={TreeSelect.SHOW_CHILD}
                searchPlaceholder={"选择部门或人员"}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="选择考勤组负责人">
            {getFieldDecorator("chargePerIdStr", {
              rules: [
                {
                  required: true,
                  message: "选择考勤组负责人"
                }
              ]
            })(
              <div style={{ position: "relative" }}>
                <Button
                  onClick={() => {
                    this.setState({ chargePerVisible: true });
                  }}
                  type="primary"
                  ghost
                  style={{ marginRight: 10 }}
                >
                  选择人员
                </Button>
                {this.state.chargePerIdList.length > 0 &&
                  this.state.chargePerIdList[0]["title"]}
              </div>
            )}
          </FormItem>
          <Divider />
          <FormItem {...submitFormLayout} style={{ marginTop: 24 }}>
            <Button
              onClick={() => {
                this.props.history.replace(
                  `/attendancemanagement/choosewayattendance?attendGroupId=${
                    this.state.attendGroupId
                  }&midAttendGroupId=${this.state.midAttendGroupId}`
                );
              }}
              loading={submitting}
            >
              返回
            </Button>
            <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">
              确认并进行下一步
            </Button>
          </FormItem>
        </Form>
        {this.renderUserSelect()}
      </div>
    );
  }
}
